Page({
  data: {
    // 100个随机单词词库
    wordBank: [
      { word: 'abandon', meaning: '放弃，抛弃', wrongMeanings: ['拥抱', '坚持', '继续'] },
      { word: 'ability', meaning: '能力，才能', wrongMeanings: ['困难', '失败', '缺陷'] },
      { word: 'about', meaning: '关于，大约', wrongMeanings: ['之前', '之后', '之外'] },
      { word: 'above', meaning: '在...之上', wrongMeanings: ['在...之下', '在...里面', '在...旁边'] },
      { word: 'accept', meaning: '接受，同意', wrongMeanings: ['拒绝', '忽略', '延迟'] },
      { word: 'account', meaning: '账户，解释', wrongMeanings: ['问题', '答案', '错误'] },
      { word: 'achieve', meaning: '实现，达到', wrongMeanings: ['失败', '放弃', '错过'] },
      { word: 'action', meaning: '行动，行为', wrongMeanings: ['想法', '梦想', '静止'] },
      { word: 'activity', meaning: '活动，行为', wrongMeanings: ['休息', '睡眠', '静默'] },
      { word: 'address', meaning: '地址，演讲', wrongMeanings: ['姓名', '年龄', '身高'] },
      { word: 'advance', meaning: '前进，进步', wrongMeanings: ['后退', '停止', '下降'] },
      { word: 'agree', meaning: '同意，一致', wrongMeanings: ['反对', '争论', '忽视'] },
      { word: 'airport', meaning: '机场', wrongMeanings: ['车站', '港口', '学校'] },
      { word: 'almost', meaning: '几乎，差不多', wrongMeanings: ['完全', '从不', '很少'] },
      { word: 'among', meaning: '在...之中', wrongMeanings: ['在...之外', '在...之前', '在...之后'] },
      { word: 'animal', meaning: '动物', wrongMeanings: ['植物', '石头', '建筑'] },
      { word: 'answer', meaning: '回答，答案', wrongMeanings: ['问题', '疑问', '困惑'] },
      { word: 'appear', meaning: '出现，似乎', wrongMeanings: ['消失', '隐藏', '离开'] },
      { word: 'around', meaning: '周围，大约', wrongMeanings: ['里面', '之外', '远处'] },
      { word: 'arrive', meaning: '到达，来临', wrongMeanings: ['离开', '错过', '推迟'] },
      { word: 'article', meaning: '文章，物品', wrongMeanings: ['标题', '结论', '摘要'] },
      { word: 'attack', meaning: '攻击，袭击', wrongMeanings: ['保护', '防守', '逃跑'] },
      { word: 'author', meaning: '作者，作家', wrongMeanings: ['读者', '编辑', '出版商'] },
      { word: 'available', meaning: '可获得的', wrongMeanings: ['不可能的', '困难的', '昂贵的'] },
      { word: 'beautiful', meaning: '美丽的', wrongMeanings: ['丑陋的', '普通的', '可怕的'] },
      { word: 'because', meaning: '因为', wrongMeanings: ['虽然', '但是', '如果'] },
      { word: 'become', meaning: '变成，成为', wrongMeanings: ['保持', '拒绝', '避免'] },
      { word: 'begin', meaning: '开始，着手', wrongMeanings: ['结束', '停止', '完成'] },
      { word: 'believe', meaning: '相信，认为', wrongMeanings: ['怀疑', '否认', '忽视'] },
      { word: 'benefit', meaning: '利益，好处', wrongMeanings: ['损失', '危害', '困难'] },
      { word: 'beside', meaning: '在...旁边', wrongMeanings: ['在...里面', '在...上面', '在...下面'] },
      { word: 'better', meaning: '更好的', wrongMeanings: ['更差的', '相同的', '最差的'] },
      { word: 'between', meaning: '在...之间', wrongMeanings: ['在...里面', '在...外面', '在...上面'] },
      { word: 'brother', meaning: '兄弟', wrongMeanings: ['姐妹', '父亲', '朋友'] },
      { word: 'business', meaning: '商业，事业', wrongMeanings: ['娱乐', '休闲', '游戏'] },
      { word: 'camera', meaning: '照相机', wrongMeanings: ['电视', '收音机', '电话'] },
      { word: 'cancel', meaning: '取消，撤销', wrongMeanings: ['确认', '继续', '开始'] },
      { word: 'capital', meaning: '首都，资本', wrongMeanings: ['乡村', '债务', '支出'] },
      { word: 'career', meaning: '职业，生涯', wrongMeanings: ['爱好', '休闲', '游戏'] },
      { word: 'century', meaning: '世纪，百年', wrongMeanings: ['十年', '千年', '一年'] },
      { word: 'certainly', meaning: '当然，确定', wrongMeanings: ['也许', '不可能', '怀疑'] },
      { word: 'challenge', meaning: '挑战，质疑', wrongMeanings: ['简单', '容易', '轻松'] },
      { word: 'chance', meaning: '机会，可能', wrongMeanings: ['确定', '不可能', '困难'] },
      { word: 'character', meaning: '性格，角色', wrongMeanings: ['情节', '背景', '结局'] },
      { word: 'choice', meaning: '选择，选项', wrongMeanings: ['命令', '要求', '强制'] },
      { word: 'citizen', meaning: '公民，市民', wrongMeanings: ['游客', '外国人', '官员'] },
      { word: 'college', meaning: '大学，学院', wrongMeanings: ['小学', '幼儿园', '工厂'] },
      { word: 'comment', meaning: '评论，意见', wrongMeanings: ['沉默', '忽视', '禁止'] },
      { word: 'common', meaning: '常见的，共同的', wrongMeanings: ['稀有的', '独特的', '特殊的'] },
      { word: 'company', meaning: '公司，陪伴', wrongMeanings: ['个人', '孤独', '分离'] },
      { word: 'compare', meaning: '比较，对比', wrongMeanings: ['复制', '忽视', '混合'] },
      { word: 'computer', meaning: '计算机', wrongMeanings: ['打字机', '计算器', '电视'] },
      { word: 'concern', meaning: '关心，担心', wrongMeanings: ['忽视', '冷漠', '开心'] },
      { word: 'condition', meaning: '条件，状况', wrongMeanings: ['结果', '原因', '目的'] },
      { word: 'conference', meaning: '会议，讨论', wrongMeanings: ['聚会', '游戏', '电影'] },
      { word: 'consider', meaning: '考虑，认为', wrongMeanings: ['忽视', '拒绝', '禁止'] },
      { word: 'continue', meaning: '继续，持续', wrongMeanings: ['停止', '结束', '暂停'] },
      { word: 'control', meaning: '控制，管理', wrongMeanings: ['失控', '混乱', '自由'] },
      { word: 'country', meaning: '国家，乡村', wrongMeanings: ['城市', '海洋', '天空'] },
      { word: 'couple', meaning: '夫妇，一对', wrongMeanings: ['单身', '群体', '团队'] },
      { word: 'create', meaning: '创造，创建', wrongMeanings: ['破坏', '复制', '删除'] },
      { word: 'culture', meaning: '文化，培养', wrongMeanings: ['自然', '本能', '野性'] },
      { word: 'current', meaning: '当前的，流行的', wrongMeanings: ['过去的', '未来的', '永远的'] },
      { word: 'customer', meaning: '顾客，客户', wrongMeanings: ['老板', '员工', '经理'] },
      { word: 'decide', meaning: '决定，判断', wrongMeanings: ['犹豫', '推迟', '忽视'] },
      { word: 'degree', meaning: '程度，学位', wrongMeanings: ['无知', '失败', '困难'] },
      { word: 'describe', meaning: '描述，描写', wrongMeanings: ['隐瞒', '忽视', '忘记'] },
      { word: 'design', meaning: '设计，图案', wrongMeanings: ['意外', '混乱', '错误'] },
      { word: 'detail', meaning: '详情，细节', wrongMeanings: ['概要', '简介', '标题'] },
      { word: 'develop', meaning: '发展，开发', wrongMeanings: ['衰退', '破坏', '停止'] },
      { word: 'difficult', meaning: '困难的', wrongMeanings: ['简单的', '容易的', '轻松的'] },
      { word: 'dinner', meaning: '晚餐，正餐', wrongMeanings: ['早餐', '零食', '饮料'] },
      { word: 'direction', meaning: '方向，指导', wrongMeanings: ['混乱', '迷失', '错误'] },
      { word: 'discover', meaning: '发现，发觉', wrongMeanings: ['隐藏', '忽视', '丢失'] },
      { word: 'discuss', meaning: '讨论，谈论', wrongMeanings: ['沉默', '忽视', '禁止'] },
      { word: 'distance', meaning: '距离，远处', wrongMeanings: ['接近', '邻近', '紧挨'] },
      { word: 'doctor', meaning: '医生，博士', wrongMeanings: ['护士', '病人', '药剂师'] },
      { word: 'during', meaning: '在...期间', wrongMeanings: ['在...之前', '在...之后', '从不'] },
      { word: 'economy', meaning: '经济，节约', wrongMeanings: ['浪费', '奢侈', '挥霍'] },
      { word: 'education', meaning: '教育，培养', wrongMeanings: ['无知', '娱乐', '游戏'] },
      { word: 'effect', meaning: '效果，影响', wrongMeanings: ['原因', '开始', '准备'] },
      { word: 'employee', meaning: '员工，雇员', wrongMeanings: ['老板', '顾客', '竞争者'] },
      { word: 'energy', meaning: '能量，精力', wrongMeanings: ['疲劳', '虚弱', '懒惰'] },
      { word: 'entire', meaning: '整个的，全部的', wrongMeanings: ['部分的', '少数的', '一些'] },
      { word: 'environment', meaning: '环境，氛围', wrongMeanings: ['个人', '内心', '想象'] },
      { word: 'especially', meaning: '特别地，尤其', wrongMeanings: ['一般地', '普通地', '很少'] },
      { word: 'evening', meaning: '晚上，傍晚', wrongMeanings: ['早晨', '中午', '深夜'] },
      { word: 'example', meaning: '例子，榜样', wrongMeanings: ['规则', '理论', '原则'] },
      { word: 'experience', meaning: '经验，体验', wrongMeanings: ['理论', '想象', '无知'] },
      { word: 'explain', meaning: '解释，说明', wrongMeanings: ['隐瞒', '混淆', '误导'] },
      { word: 'family', meaning: '家庭，家族', wrongMeanings: ['陌生人', '敌人', '竞争者'] },
      { word: 'famous', meaning: '著名的，有名的', wrongMeanings: ['无名的', '普通的', '默默无闻的'] },
      { word: 'father', meaning: '父亲，爸爸', wrongMeanings: ['母亲', '孩子', '朋友'] },
      { word: 'feature', meaning: '特征，特色', wrongMeanings: ['缺陷', '普通', '一般'] },
      { word: 'feeling', meaning: '感觉，情感', wrongMeanings: ['理性', '逻辑', '冷漠'] },
      { word: 'finally', meaning: '最后，终于', wrongMeanings: ['首先', '开始', '永不'] },
      { word: 'finger', meaning: '手指', wrongMeanings: ['脚趾', '手掌', '手臂'] },
      { word: 'finish', meaning: '完成，结束', wrongMeanings: ['开始', '继续', '暂停'] },
      { word: 'flower', meaning: '花，开花', wrongMeanings: ['叶子', '根', '树干'] },
      { word: 'follow', meaning: '跟随，遵循', wrongMeanings: ['领导', '反对', '拒绝'] },
      { word: 'forget', meaning: '忘记，遗忘', wrongMeanings: ['记住', '回忆', '学习'] },
      { word: 'friend', meaning: '朋友，友人', wrongMeanings: ['敌人', '陌生人', '竞争者'] },
      { word: 'future', meaning: '未来，将来', wrongMeanings: ['过去', '现在', '永远'] },
      { word: 'garden', meaning: '花园，菜园', wrongMeanings: ['沙漠', '海洋', '天空'] },
      { word: 'general', meaning: '一般的，将军', wrongMeanings: ['特殊的', '士兵', '具体的'] },
      { word: 'government', meaning: '政府，管理', wrongMeanings: ['个人', '混乱', '无政府'] },
      { word: 'ground', meaning: '地面，土地', wrongMeanings: ['天空', '海洋', '云彩'] },
      { word: 'happen', meaning: '发生，碰巧', wrongMeanings: ['预防', '避免', '计划'] },
      { word: 'health', meaning: '健康，卫生', wrongMeanings: ['疾病', '虚弱', '残疾'] },
      { word: 'history', meaning: '历史，经历', wrongMeanings: ['未来', '现在', '预测'] },
      { word: 'holiday', meaning: '假期，节日', wrongMeanings: ['工作日', '上班', '学习'] },
      { word: 'hospital', meaning: '医院', wrongMeanings: ['学校', '商店', '餐厅'] },
      { word: 'however', meaning: '然而，无论如何', wrongMeanings: ['因此', '所以', '当然'] }
    ],
    
    // 当前学习状态
    currentWordIndex: 0,
    currentWord: null,
    options: [],
    selectedOption: -1,
    showResult: false,
    isCorrect: false,
    studyStartTime: null,
    studiedWords: [],
    correctCount: 0,
    wrongCount: 0,
    isStarred: false,
    
    // 学习进度
    totalQuestions: 20, // 默认20个单词，会从用户设置中读取
    currentQuestion: 1,
    
    // 学习模式：normal(正常) 或 wrong(错题)
    studyMode: 'normal',
    wrongWordsBank: [] // 错题本单词库
  },

  onLoad: function(options) {
    // 检查是否是错题学习模式
    if (options.type === 'wrong') {
      this.setData({
        studyMode: 'wrong'
      });
      this.loadWrongWords();
    } else {
      this.setData({
        studyMode: 'normal'
      });
    }
    
    this.loadUserSettings();
    this.initStudy();
  },

  // 加载错题本单词
  loadWrongWords: function() {
    const wrongWords = wx.getStorageSync('wrongWords') || [];
    
    // 将错题本单词转换为学习格式
    const wrongWordsBank = wrongWords.map(item => {
      const word = typeof item === 'string' ? item : item.word;
      const meaning = item.meaning || '暂无释义';
      
      // 为错题本单词生成错误选项
      const wrongMeanings = this.generateWrongMeanings(meaning);
      
      return {
        word: word,
        meaning: meaning,
        wrongMeanings: wrongMeanings
      };
    });
    
    this.setData({
      wrongWordsBank: wrongWordsBank,
      totalQuestions: wrongWordsBank.length // 错题学习时，学习所有错题
    });
  },

  // 为错题单词生成错误选项
  generateWrongMeanings: function(correctMeaning) {
    // 从wordBank中随机选择3个不同的释义作为错误选项
    const allMeanings = this.data.wordBank.map(word => word.meaning);
    const wrongMeanings = [];
    
    while (wrongMeanings.length < 3) {
      const randomMeaning = allMeanings[Math.floor(Math.random() * allMeanings.length)];
      if (randomMeaning !== correctMeaning && !wrongMeanings.includes(randomMeaning)) {
        wrongMeanings.push(randomMeaning);
      }
    }
    
    return wrongMeanings;
  },

  // 加载用户设置
  loadUserSettings: function() {
    const userSettings = wx.getStorageSync('userSettings') || {};
    const dailyTarget = userSettings.dailyTarget || 20;
    
    this.setData({
      totalQuestions: dailyTarget
    });
  },

  // 初始化学习
  initStudy: function() {
    this.setData({
      studyStartTime: new Date(),
      studiedWords: [],
      correctCount: 0,
      wrongCount: 0,
      currentQuestion: 1
    });
    this.generateQuestion();
  },

  // 生成题目
  generateQuestion: function() {
    const { wordBank, wrongWordsBank, studiedWords, totalQuestions, studyMode } = this.data;
    
    // 根据学习模式选择单词库
    const currentWordBank = studyMode === 'wrong' ? wrongWordsBank : wordBank;
    
    // 错题学习模式下，如果没有错题，提示并返回
    if (studyMode === 'wrong' && currentWordBank.length === 0) {
      wx.showModal({
        title: '提示',
        content: '错题本中没有单词，无法开始学习',
        showCancel: false,
        success: () => {
          wx.navigateBack();
        }
      });
      return;
    }
    
    let availableWords;
    if (studyMode === 'wrong') {
      // 错题学习模式：直接使用当前错题库（已答对的会被移除）
      availableWords = currentWordBank;
    } else {
      // 正常学习模式：从未学习的单词中选择
      availableWords = currentWordBank.filter(word => 
        !studiedWords.some(studied => studied.word === word.word)
      );
    }
    
    if (availableWords.length === 0) {
      // 所有单词都已学习完成
      this.finishStudy();
      return;
    }
    
    // 随机选择一个单词
    const randomIndex = Math.floor(Math.random() * availableWords.length);
    const currentWord = availableWords[randomIndex];
    
    // 生成四个选项（1个正确答案 + 3个错误答案）
    const options = [currentWord.meaning, ...currentWord.wrongMeanings];
    
    // 打乱选项顺序
    for (let i = options.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [options[i], options[j]] = [options[j], options[i]];
    }
    
    // 检查是否收藏 - 检查两个存储位置
    const profileCollectedWords = wx.getStorageSync('wordsCollection') || [];
    const vocabularyCollectedWords = wx.getStorageSync('wordCollections') || [];
    
    const isStarredInProfile = profileCollectedWords.some(item => {
      const word = typeof item === 'string' ? item : item.word;
      return word === currentWord.word;
    });
    
    const isStarredInVocabulary = vocabularyCollectedWords.some(item => {
      const word = typeof item === 'string' ? item : item.word;
      return word === currentWord.word;
    });
    
    // 如果在任一位置被收藏，则显示为已收藏
    const isStarred = isStarredInProfile || isStarredInVocabulary;
    
    this.setData({
      currentWord: currentWord,
      options: options,
      selectedOption: -1,
      showResult: false,
      isCorrect: false,
      isStarred: isStarred
    });
  },

  // 选择答案
  selectOption: function(e) {
    if (this.data.showResult) return;
    
    const index = parseInt(e.currentTarget.dataset.index);
    const selectedMeaning = this.data.options[index];
    const isCorrect = selectedMeaning === this.data.currentWord.meaning;
    
    this.setData({
      selectedOption: index,
      showResult: true,
      isCorrect: isCorrect
    });
    
    // 记录学习结果
    const studiedWord = {
      word: this.data.currentWord.word,
      meaning: this.data.currentWord.meaning,
      isCorrect: isCorrect,
      studyTime: new Date().toISOString()
    };
    
    this.setData({
      studiedWords: [...this.data.studiedWords, studiedWord],
      correctCount: isCorrect ? this.data.correctCount + 1 : this.data.correctCount,
      wrongCount: !isCorrect ? this.data.wrongCount + 1 : this.data.wrongCount
    });
    
    // 处理错题本逻辑
    if (this.data.studyMode === 'wrong') {
      // 错题学习模式：如果答对了，从错题本中移除
      if (isCorrect) {
        this.removeFromWrongWords(studiedWord.word);
      }
    } else {
      // 正常学习模式：如果答错了，添加到错题本
      if (!isCorrect) {
        this.addToWrongWords(studiedWord);
      }
    }
    
    // 2秒后显示下一题
    setTimeout(() => {
      this.nextQuestion();
    }, 2000);
  },

  // 下一题
  nextQuestion: function() {
    // 错题学习模式：检查是否还有错题需要学习
    if (this.data.studyMode === 'wrong') {
      if (this.data.wrongWordsBank.length === 0) {
        this.finishStudy();
      } else {
        this.generateQuestion();
      }
    } else {
      // 正常学习模式：检查是否达到目标题数
      if (this.data.studiedWords.length >= this.data.totalQuestions) {
        this.finishStudy();
      } else {
        this.generateQuestion();
      }
    }
  },

  // 添加到错题本
  addToWrongWords: function(word) {
    const wrongWords = wx.getStorageSync('wrongWords') || [];
    const exists = wrongWords.some(item => {
      const wordText = typeof item === 'string' ? item : item.word;
      return wordText === word.word;
    });
    
    if (!exists) {
      const wrongWord = {
        word: word.word,
        meaning: word.meaning,
        addTime: this.formatTime(new Date())
      };
      wrongWords.push(wrongWord);
      wx.setStorageSync('wrongWords', wrongWords);
    }
  },

  // 从错题本移除单词
  removeFromWrongWords: function(word) {
    const wrongWords = wx.getStorageSync('wrongWords') || [];
    const filteredWords = wrongWords.filter(item => {
      const wordText = typeof item === 'string' ? item : item.word;
      return wordText !== word;
    });
    wx.setStorageSync('wrongWords', filteredWords);
    
    // 如果是错题学习模式，更新总题数和错题库
    if (this.data.studyMode === 'wrong') {
      const updatedWrongWordsBank = this.data.wrongWordsBank.filter(item => item.word !== word);
      this.setData({
        wrongWordsBank: updatedWrongWordsBank,
        totalQuestions: updatedWrongWordsBank.length
      });
    }
  },

  // 切换收藏状态
  toggleStar: function() {
    const { currentWord, isStarred } = this.data;
    
    // Profile页面收藏数据 (新格式)
    let profileCollectedWords = wx.getStorageSync('wordsCollection') || [];
    
    // Vocabulary页面收藏数据 (旧格式)
    let vocabularyCollectedWords = wx.getStorageSync('wordCollections') || [];
    
    if (isStarred) {
      // 取消收藏 - 从两个存储中都移除
      profileCollectedWords = profileCollectedWords.filter(item => {
        const word = typeof item === 'string' ? item : item.word;
        return word !== currentWord.word;
      });
      
      vocabularyCollectedWords = vocabularyCollectedWords.filter(item => {
        const word = typeof item === 'string' ? item : item.word;
        return word !== currentWord.word;
      });
      
      this.setData({ isStarred: false });
      wx.showToast({
        title: '已取消收藏',
        icon: 'none'
      });
    } else {
      // 添加收藏 - 保存到两个存储中
      
      // Profile页面格式
      const profileCollectedWord = {
        word: currentWord.word,
        phonetic: '', // word-study页面没有音标信息
        meaning: currentWord.meaning,
        chineseTranslation: currentWord.meaning,
        collectTime: this.formatTime(new Date())
      };
      profileCollectedWords.unshift(profileCollectedWord);
      
      // Vocabulary页面格式
      const vocabularyCollectedWord = {
        word: currentWord.word,
        meaning: currentWord.meaning,
        addTime: this.formatTime(new Date())
      };
      vocabularyCollectedWords.unshift(vocabularyCollectedWord);
      
      this.setData({ isStarred: true });
      wx.showToast({
        title: '已添加收藏',
        icon: 'success'
      });
    }
    
    // 保存到两个不同的存储键
    wx.setStorageSync('wordsCollection', profileCollectedWords);
    wx.setStorageSync('wordCollections', vocabularyCollectedWords);
  },

  // 完成学习
  finishStudy: function() {
    const { studyStartTime, studiedWords, correctCount, wrongCount } = this.data;
    const endTime = new Date();
    const duration = Math.round((endTime.getTime() - studyStartTime.getTime()) / 1000 / 60); // 分钟
    
    // 更新学习统计
    this.updateStudyStats(studiedWords.length, duration);
    
    // 保存学习记录
    this.saveStudyRecord(studiedWords);
    
    // 显示结果
    const accuracy = studiedWords.length > 0 ? Math.round((correctCount / studiedWords.length) * 100) : 0;
    const isWrongMode = this.data.studyMode === 'wrong';
    
    let title, targetText;
    if (isWrongMode) {
      title = '错题学习完成！';
      targetText = '所有错题都已掌握！';
    } else {
      title = '学习完成！';
      targetText = '已完成今日目标！';
    }
    
    wx.showModal({
      title: title,
      content: `✅ ${targetText}\n📚 学习单词：${studiedWords.length}个\n✅ 正确：${correctCount}个\n❌ 错误：${wrongCount}个\n📊 正确率：${accuracy}%\n⏰ 用时：${duration}分钟`,
      showCancel: false,
      confirmText: '确定',
      success: () => {
        wx.navigateBack();
      }
    });
  },

  // 更新学习统计
  updateStudyStats: function(learnedCount, duration) {
    const today = this.formatDate(new Date());
    const studyStats = wx.getStorageSync('studyStats') || {};
    
    if (!studyStats[today]) {
      studyStats[today] = { learned: 0, duration: 0 };
    }
    
    studyStats[today].learned += learnedCount;
    studyStats[today].duration += duration;
    
    wx.setStorageSync('studyStats', studyStats);
  },

  // 保存学习记录
  saveStudyRecord: function(studiedWords) {
    const studyRecords = wx.getStorageSync('studyRecords') || [];
    const now = new Date();
    const duration = Math.round((now.getTime() - this.data.studyStartTime.getTime()) / 1000 / 60); // 分钟
    const { correctCount, wrongCount } = this.data;
    const wordsLearned = studiedWords.length;
    const correctRate = wordsLearned > 0 ? Math.round((correctCount / wordsLearned) * 100) : 0;
    
    const record = {
      timestamp: now.toISOString(), // 用于排序
      date: this.formatDate(now), // 显示用的日期 "2024-01-01"
      time: this.formatTime(now), // 显示用的时间 "1月1日 14:30"
      wordsLearned: wordsLearned, // 学习单词数
      correctRate: correctRate, // 正确率
      duration: duration, // 学习时长(分钟)
      details: `学习了${wordsLearned}个单词，正确${correctCount}个，错误${wrongCount}个`,
      words: studiedWords // 详细单词列表
    };
    
    studyRecords.unshift(record);
    // 只保留最近100条记录
    if (studyRecords.length > 100) {
      studyRecords.splice(100);
    }
    
    wx.setStorageSync('studyRecords', studyRecords);
  },

  // 格式化日期 (用于显示)
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    
    if (this.isSameDay(date, today)) {
      return '今天';
    } else if (this.isSameDay(date, yesterday)) {
      return '昨天';
    } else {
      return `${year}年${month}月${day}日`;
    }
  },
  
  // 判断是否为同一天
  isSameDay: function(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate();
  },

  // 格式化时间
  formatTime: function(date) {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    return `${month}月${day}日 ${hour}:${minute.toString().padStart(2, '0')}`;
  },

  // 返回上一页
  goBack: function() {
    wx.showModal({
      title: '确认退出',
      content: '退出将不会保存学习进度，确定要退出吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack();
        }
      }
    });
  }
}); 